<template>
  <base-breadcrumb>
    <div class="about-master-container">
      <a-card v-loading="loading">
        <title-name title="基本信息" />
        <BForm
          ref="form"
          :is-detail="false"
          :config="formConfig"
          :form="form"
          :rule="formRules"
        />
      </a-card>
      <a-card
        v-if="disabled"
        v-loading="loading"
      >
        <title-name title="印章回收记录" />
        <b-table
          ref="table"
          :scroll="{ x: 1376 }"
          :request="loadData"
          :columns="recycleSealsColumns"
          :show-page="false"
          :export-config="{ use: true,select: this.form.depName+'印章',all: this.form.depName+'印章'}"
        >
          <span
            slot="index"
            slot-scope="text, record, index"
          >{{ index + 1 }}</span>
        </b-table>
      </a-card>
      <div class="tar page-btn-right-top">
        <a-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          class="mr10p"
          @click="save('DRAFT',false)"
        >
          提交
        </a-button>
        <a-button
          v-checkVisibleInDetail
          @click="$close"
        >
          关闭
        </a-button>
      </div>
    </div>
  </base-breadcrumb>
</template>

<script>
import SelectTreeUnion from '@/components/Select/SelectTreeUnion'
import SelectUnionPeople from '@/components/Select/SelectUnionPeople'
import BSelect from '@/components/BComponents/BSelect'
import projectApi from '@/api/office/seal/project'
import { getAuditProject } from '@/api/themeChoose/themeChoose'
import { getOneOrgUsers } from '@/api/commons'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import { getDepartmentList } from '@/api/businessAffairs/revenueAndCost'

export default {
  components: {
    SelectTreeUnion,
    SelectUnionPeople,
    BSelect
  },
  computed: {
    formConfig() {
      return [
        {
          row: true,
          children: [
            {
              type: SelectCompanyAndProject,
              value: 'depId',
              label: '单位名称',
              attrs: {
                disabled: true,
                autoSelect: !this.$route.query.id
              },
              on: {
                onSelectChange: this.depChange
              }
            },
            {
              type: 'date-picker',
              value: 'completionTime',
              label: '项目计划竣工时间',
              attrs: {
                disabled: true,
                valueFormat: 'x'
              }
            },
            { type: 'input', value: 'sealName', label: '印章名称', attrs: { disabled: this.disabled } },
            {
              type: 'select',
              value: 'departmentId',
              label: '保管部门',
              attrs: {
                disabled: this.disabled,
                data: this.options.departments
              },
              on: {
                change: this.departmentChange
              }
            },
            {
              type: 'select',
              value: 'preserverId',
              label: '保管人',
              attrs: {
                key: ['name', 'userId'],
                disabled: this.disabled,
                data: this.options.persons
              },
              on: {
                change: this.personChange
              }
            },
            { type: 'input', value: 'preserverPhone', label: '联系电话', attrs: { disabled: this.disabled } },
            {
              type: 'select',
              value: 'sealStatus',
              label: '印章状态',
              attrs: {
                disabled: this.disabled,
                data: [
                  { name: '完好', id: '完好' },
                  { name: '损毁', id: '损毁' },
                  { name: '丢失', id: '丢失' },
                  { name: '其他', id: '其他' }
                ]
              }
            },
            {
              type: 'input',
              value: 'otherStatus',
              label: '其他状态',
              attrs: { disabled: this.disabled },
              show: this.form.sealStatus === '其他'
            }
          ]
        },
        {
          row: true,
          children: [
            {
              type: 'custom',
              value: 'liabilityFile',
              label: '保管责任书',
              colSpan: 8,
              noFixed: true,
              render: () => {
                return (
                  <div>
                    <b-upload2 uploadType="single" disabled={this.disabled} businessCode="UN09" v-model={this.form.liabilityFile} />
                    {this.disabled || <span style="font-size:14px;color:#999;">请上传分公司与印章保管人签订的保管责任书</span>}
                  </div>
                )
              }
            },
            {
              type: 'custom',
              value: 'establishFile',
              label: '项目成立文件',
              colSpan: 8,
              noFixed: true,
              render: () => {
                return (
                  <div>
                    <b-upload2 uploadType="single" disabled={this.disabled} businessCode="UN09" v-model={this.form.establishFile} />
                    {this.disabled || <span style="font-size:14px;color:#999;">请上传局印发的项目部成立文件</span>}
                  </div>
                )
              }
            },
            {
              type: 'custom',
              value: 'preserverFile',
              label: '保管人责任书',
              colSpan: 8,
              noFixed: true,
              render: () => {
                return (
                  <div>
                    <b-upload2 uploadType="single" disabled={this.disabled} businessCode="UN09" v-model={this.form.preserverFile} />
                    {this.disabled || <span style="font-size:14px;color:#999;">请上传项目部与印章保管人签定的保管责任书</span>}
                  </div>
                )
              }
            }
          ]
        }
      ]
    }
  },

  data() {
    let validatePhone = (rule, value, callback) => {
      if (!/^1\d{10}$/.test(value)) {
        callback('保管人电话格式不正确')
      } else {
        callback()
      }
    }
    return {
      disabled: this.$route.query.detail == 1,
      isFirst: true,
      loading: false,
      form: {
        branchComId: '',
        companyId: null,
        completionTime: '',
        depId: '',
        depName: '',
        departmentId: '',
        departmentName: '',
        otherStatus: null,
        preserverId: '',
        preserverName: '',
        preserverPhone: '',
        projectId: '',
        projectName: '',
        sealName: '',
        sealStatus: undefined,
        projectTime: null,
        recycleStatus: '',
        liabilityFile: [],
        establishFile: [],
        recycleSeals: [],
        preserverFile: []
      },
      formRules: {
        establishFile: { type: 'array', required: true, message: '项目成立文件不能为空', trigger: 'change' },
        liabilityFile: {
          type: 'array',
          required: true,
          message: '请上传分公司与项目经理签定的保管责任书',
          trigger: 'change'
        },
        preserverFile: {
          type: 'array',
          required: true,
          message: '请上传项目部与印章保管人签定的保管责任书',
          trigger: 'change'
        },
        depId: { required: true, message: '单位不能为空', trigger: 'blur' },
        departmentId: { required: true, message: '保管部门不能为空', trigger: 'change' },
        otherStatus: { required: true, message: '其他状态不能为空', trigger: 'blur' },
        preserverId: { required: true, message: '保管人不能为空', trigger: 'blur' },
        preserverPhone: [{ required: true, validator: validatePhone, trigger: 'change' }],
        sealName: { required: true, message: '印章名称不能为空', trigger: 'change' },
        sealStatus: { required: true, message: '印章状态不能为空', trigger: 'change' }
      },
      options: {
        departments: [],
        persons: []
      },
      recycleSealsColumns: [
        { title: '序号', scopedSlots: { customRender: 'index' }, width: 70 },
        { title: '上交单位', dataIndex: 'handInDepName', width: 150 },
        { title: '上交人', dataIndex: 'handInName', width: 120 },
        { title: '上交人电话', dataIndex: 'handInPhone', width: 150 },
        { title: '印章状态', dataIndex: 'sealStatus', width: 150 },
        { title: '回收人', dataIndex: 'recyleName', width: 120 },
        { title: '回收人电话', dataIndex: 'recyclePhone', width: 150 },
        { title: '回收时间', dataIndex: 'recycleTime', width: 150 },
        { title: '回收原因', dataIndex: 'recyleReason', width: 350 },
        { title: '备注', dataIndex: 'remark', width: 350 }
      ],
      loadData: () => {
        return {
          code: 200,
          data: this.form.recycleSeals,
          totalSize: this.form.recycleSeals ? this.form.recycleSeals.length : 0
        }
      }
    }
  },
  created: async function () {
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id
      await this.getBaseInfo()
    }
  },
  methods: {
    async departmentChange(e) {
      if (this.options.departments.length > 0) {
        this.form.departmentName = this.options.departments.find((v) => v.id === e).name
      }

      let res = await getOneOrgUsers({
        pageNumber: 1,
        pageSize: 10000,
        queryPostRelation: true,
        rootOrgId: e
      })
      if (res.code === this.SUCCESS_CODE) {
        this.options.persons = res.data.list || []
        if (this.$route.query.id && this.isFirst) return (this.isFirst = false)
        this.form.preserverId = ''
        this.form.preserverPhone = ''
        this.form.preserverName = ''
        let res2 = this.options.persons.find((v) => v.userId === this.$userInfo().id)
        if (res2) {
          this.form.preserverId = res2.userId
          await this.personChange(res2.userId)
        }
      }
    },
    async personChange(e) {
      if (this.$route.query.id && this.isFirst) return (this.isFirst = false)
      let res2 = this.options.persons.find((v) => v.userId === e)
      if (res2) {
        this.form.preserverPhone = res2.phone
        this.form.preserverName = res2.name
      }
    },
    async depChange(e) {
      this.form.depId = e.id
      this.form.depName = e.name
      this.form.branchComId = e.parentId
      this.form.branchComName = e.parentName
      let res3 = await getDepartmentList({
        id: this.form.depId,
        type: '2'
      })
      this.fetching = false
      this.options.departments = res3.data || []
      if (this.$route.query.id) return

      let res2 = this.options.departments.find((v) => v.id === this.$currentPost().deptId)
      if (res2) {
        this.form.departmentId = res2.id
        this.departmentChange(res2.id)
        this.form.departmentName = res2.name
      }

      let res = await getAuditProject({ auditStatus: 2, projectStatus: '1,2,3,4,5,6' })
      if (res.code === 200) {
        if (this.$route.query.id) return
        this.form.completionTime = new Date(res.data[0].contractFinishDate).valueOf() + ''
        this.form.projectTime = res.data[0].completionTime
        this.form.projectId = res.data[0].projectDeptId
        this.form.projectName = res.data[0].projectName
      }
    },
    async getBaseInfo() {
      this.loading = true
      let res = await projectApi.findById({}, { id: this.form.id })
      if (res.code === this.SUCCESS_CODE) {
        this.form = res.data
        if (this.isFirst) {
          this.depChange({
            id: this.form.depId,
            name: this.form.depName,
            parentId: this.form.branchComId,
            parentName: this.form.branchComName
          })
          this.departmentChange(this.form.departmentId)
        }
        this.form.recycleSeals = this.form.recycleSeals ? this.form.recycleSeals : []
        this.form.preserverFile = this.form.preserverFile ? this.form.preserverFile : []
        if (this.disabled) {
          this.$refs.table.getData(null, true)
        }
      }
      this.loading = false
    },
    async submit() {
      if (!(await this.save('DRAFT', true))) {
        return
      }
      if (await this.save('SUBMITTED', true)) {
        this.$close()
      }
    },
    async save(auditStatus, isSubmit = false) {
      this.$console(this.form)
      return new Promise((resolve) => {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            this.loading = true
            let res
            let temp = this.$clone(this.form)
            temp.auditStatus = auditStatus
            if (temp.entryTime) {
              temp.entryTime = new Date(temp.entryTime).valueOf()
            }
            if (temp.id) {
              res = await projectApi.update(temp)
            } else {
              res = await projectApi.add(temp)
            }
            if (res.code === 200) {
              if (auditStatus === 'DRAFT') {
                this.$message.success('提交成功')
              } else {
                this.$message.success('提交成功')
              }
              this.form.id = res.data.id
              await this.getBaseInfo()
              if (!isSubmit) {
                this.$close()
              }
              resolve(true)
            }
            this.loading = false
          }else {
            this.$message.warning("请填写完所有必填项信息")
          }
        })
      })
    }
  }
}
</script>
